import React, {useState} from 'react';
import {Button, Divider, Form, Input, Message,Checkbox,Dialog } from '@alifd/next';
import {APP_MODE, config, request, useHistory} from 'ice';

import {useInterval} from './utils';
import styles from './index.module.scss';

const {Item} = Form;


export interface IDataSource {
  userName: string;
  password: string;
  autoLogin: boolean;
  phone: string;
  code: string;
}

const DEFAULT_DATA: IDataSource = {
  userName: '',
  password: '',
  autoLogin: true,
  phone: '',
  code: '',
};

// eslint-disable-next-line @typescript-eslint/interface-name-prefix
interface LoginProps {
  dataSource?: IDataSource;
}


const LoginBlock: React.FunctionComponent<LoginProps> = (props = {dataSource: DEFAULT_DATA}): JSX.Element => {
  const {
    dataSource = DEFAULT_DATA,
  } = props;

  const history = useHistory();
  const [postData, setValue] = useState(dataSource);
  const [isRunning, checkRunning] = useState(false);
  const [isPhone, checkPhone] = useState(false);
  const [second, setSecond] = useState(59);
  const [initState, setIpState] = useState(false);
  // 是否能够使用帐号密码登录
  const [canUseNPLogin, setNPS] = useState(false);
  // 注册
  const [registerVisible, setRegisterVisible] = useState(false);

  if (!initState) {
    // console.log(APP_MODE);
    // // 查询服务器最新版本 如果和当前版本不一致 跳转 如果是线下版本 永远不执行
    // if (APP_MODE !== 'start') {
    //   getVersion();
    // }
    // 没有在倒计时 访问服务器 查询IP状态 并设置目前登录方式
    // getIpState();
  }

  useInterval(() => {
    setSecond(second - 1);
    if (second <= 0) {
      checkRunning(false);
      setSecond(59);
    }
  }, isRunning ? 1000 : null);

  async function getIpState() {
    // 不再移除登录状态
    // localStorage.removeItem('token');
    try {
      const data = await request({
        url: '/v1/auth/ip/state',
        method: 'get',
      });
      setIpState(true);
      if (data.data === true) {
        checkPhone(false);
      } else {
        checkPhone(true);
      }
      setNPS(data.data);
    } catch (error) {
      console.error(error);
    }
  }

  async function getVersion() {
    // try {
    //   const data = await request({
    //     url: '/v1/auth/version/',
    //     method: 'get',
    //   });
    //   console.log(data);
    //   if (data) {
    //     if (data.data) {
    //       if (config.version !== data.data) {
    //         // 进行页面跳转
    //         // eslint-disable-next-line react-hooks/rules-of-hooks
    //         window.location.href = `${config.ossHost + data.data}/index.html#/user/login`;
    //       }
    //     }
    //   }
    // } catch (error) {
    //   console.error(error);
    // }
  }

  const formChange = (values: IDataSource) => {
    setValue(values);
  };

  // 获得验证码
  const sendCode = async (values: IDataSource, errors: []) => {
    if (errors) {
      return;
    }
    // phone code
    const newVar = await request({
      url: '/v1/system/sms/',
      method: 'post',
      data: {
        mobileNumber: values.phone,
        type: 'login'
      }
    });
    if (!newVar.statusCode || newVar.statusCode !== 200) {
      // doNothing
    } else {
      // get values.phone
      checkRunning(true);
    }
  };

  // 进入首页 当用户拥有token时 可以无条件进入
  const clearToken = async () => {
    // 移除登录状态
    localStorage.removeItem('token');
  };

  // 进入首页 当用户拥有token时 可以无条件进入
  const intoIndex = async () => {

    const newVar = await request({
      url: '/v1/dashboard',
      method: 'get',
    });
    if (!newVar.statusCode || newVar.statusCode !== 200) {
      Message.error('登录失效,请重新登录');
    } else {
      Message.success('登录成功');
      history.push(config.mainPage);
    }
  };

  async function login(values: IDataSource, type: number) {
    console.log(values);
    if (!isPhone) {
      try {
        const data = await request({
          url: `/v1/auth/${type}`,
          method: 'post',
          data: values,
        });

        // eslint-disable-next-line eqeqeq
        if (data.statusCode == 200) {
          // 保存token
          localStorage.setItem('token', data.data.jwt);
          localStorage.setItem('userName', data.data.userName);
          // 进行跳转
          Message.success('登录成功');
          history.push(config.mainPage);
        }
      } catch (error) {
        console.error(error);
      }
    } else {
      // 使用手机登录
      try {
        const data = await request({
          url: '/v1/auth/0',
          method: 'post',
          data: {
            mobileNum: values.phone,
            code: values.code
          },
        });

        // eslint-disable-next-line eqeqeq
        if (data.statusCode == 200) {
          // 保存token
          localStorage.setItem('token', data.data.jwt);
          localStorage.setItem('userName', data.data.userName);
          // 进行跳转
          Message.success('登录成功');
          history.push(config.mainPage);
        }
      } catch (error) {
        console.error(error);
      }
    }

  }

  const handleSubmit = (values: IDataSource, errors: []) => {
    // 移除TOKEN
    localStorage.removeItem('token');
    if (errors) {
      console.log('errors', errors);
      return;
    }
    login(values, 1);
    // console.log('values:', values);
    // 进行登录 成功后 指向首页
  };

  const phoneForm = <>
    <Item format="tel" required requiredMessage="必填" asterisk={false}>
      <Input
        name="phone"
        innerBefore={<span className={styles.innerBeforeInput}>+86<span className={styles.line}/></span>}
        maxLength={20}
        placeholder="手机号"
      />
    </Item>
    <Item required requiredMessage="必填" style={{marginBottom: 0}}>
      <Input
        name="code"
        innerAfter={<span className={styles.innerAfterInput}>
          <span className={styles.line}/>
          <Form.Submit
            text
            type="primary"
            style={{width: 64}}
            disabled={isRunning}
            validate={['phone']}
            onClick={sendCode}
            className={styles.sendCode}
          >
            {isRunning ? `${second}秒后再试` : '获取验证码'}
          </Form.Submit>
        </span>}
        maxLength={20}
        placeholder="验证码"
      />
    </Item>
  </>;

  const accountForm = <>
    <Item required requiredMessage="必填">
      <Input
        name="userName"
        maxLength={20}
        placeholder="手机号"
      />
    </Item>
    <Item required requiredMessage="必填" style={{marginBottom: 0}}>
      <Input.Password
        name="password"
        htmlType="password"
        placeholder="密码"
      />
    </Item>
  </>;

  // const byAccount = () => {
  //   // eslint-disable-next-line eqeqeq
  //   if (canUseNPLogin) {
  //     checkPhone(false);
  //   } else {
  //     Message.error('您的环境不支持此登录方式')
  //   }
  // };

  // const byForm = () => {
  //   checkPhone(true);
  // };

  const onOk = () => {
    console.log('ok');
  };

  const closeRegister =()=>{
    setRegisterVisible(false)
  }

  const openRegister =()=>{
    history.push('/user/register');
  }


  return (
    <div className={styles.LoginBlock}>
      <div className={styles.innerBlock}>
        {/* <a href="#">
                   <img
            // className={styles.logo}
            className={styles.desc}
            src='public\favicon.png'
            // alt="logo"
          />
        </a> */}
        <div className={styles.desc}>
          {/* <span onClick={byAccount} className={isPhone ? undefined : styles.active}>账户密码登录</span> */}


          <span className={styles.active}>手机号码登录</span>
          <Divider direction="ver"/>
          <img
            // className={styles.logo}
            className={styles.desc}
            src='public\favicon.png'
            alt="logo"
          />
          {/* <span onClick={byForm} className={isPhone ? styles.active : undefined}>手机号登录</span> */}
        </div>

        <Form
          value={postData}
          onChange={formChange}
          size="large"
        >
          {isPhone ? phoneForm : accountForm}

                   <div className={styles.infoLine}>
            <Item style={{marginBottom: 0}}>
              <Checkbox name="autoLogin" className={styles.infoLeft}>自动登录</Checkbox>
            </Item>
            <div>
              <Button size='small' type="secondary" onClick={openRegister}>注册</Button>
            </div>

            <Dialog
                    title="注册账号"
                    visible={registerVisible}
                    onOk={onOk}
                    onCancel={closeRegister}
                    onClose={closeRegister}>
                    Start your business here by searching a popular product
            </Dialog>
          </div>

          {/* <Item style={{marginBottom: 10, marginTop: 10}}> */}
            {/* <div className={styles.infoLine}> */}
              {/* <a  className={styles.link} onClick={clearToken}>清除登录状态</a> */}
              {/* <Button  size='small' type="secondary"  onClick={clearToken}>清除登录状态</Button> */}
              {/* <Button size='small' type="secondary" onClick={intoIndex}>注册</Button> */}
            {/* </div> */}
          {/* </Item> */}



          <Item style={{marginBottom: 10}}>
            <Form.Submit
              type="primary"
              onClick={handleSubmit}
              className={styles.submitBtn}
              validate
            >
              登录
            </Form.Submit>
          </Item>

        </Form>
      </div>
    </div>
  );
}

export default LoginBlock;
